package com.bobo.dao.topicTag;

import com.bobo.dao.BaseDao;
import com.bobo.model.*;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by bobo on 16-10-28.
 */
public class TopicTagDaoImpl extends BaseDao implements ITopicTagDao{
    @Override
    public Integer create(TopicTag topicTag) {
        String sql = "INSERT INTO t_topic_tag(topic_id,tag_id)VALUES (?,?)";
        return create(sql,topicTag.getTopicId(),topicTag.getTagId());
    }

    @Override
    public boolean delete(TopicTag topicTag) {
        String sql = "DELETE FROM t_topic_tag WHERE topic_id=?";
        return update(sql,topicTag.getTopicId());
    }

    @Override
    public List<Tag> getTags(Integer topicId) {
        String sql = "SELECT tt.id,tt.name FROM t_topic_tag ttt,t_tag tt " +
                " WHERE ttt.tag_id=tt.id  AND ttt.topic_id=?";
        List<Tag> tags = new ArrayList<>();
        ResultSet rs = getObject(sql, topicId);
        try {
            while(rs.next()){
                Tag tag = new Tag();
                tag.setId(rs.getInt("id"));
                tag.setName(rs.getString("name"));
                tags.add(tag);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tags;
    }

    @Override
    public List<Topic> getTopics(Integer tagId,Integer current, Integer pageSize) {
        String sql = "SELECT vt.topic_id,vt.category_name,vt.describe,vt.title,vt.img\n" +
                " FROM t_topic_tag tt\n" +
                "  LEFT JOIN v_topic vt ON vt.topic_id=tt.topic_id\n" +
                " where vt.status=1 AND tt.tag_id=? ORDER BY vt.topic_id DESC ";
        List<Topic> topics = new ArrayList<>();
        ResultSet rs = pager(sql,current,pageSize,tagId);
        try {
            while(rs.next()){
                Topic topic = new Topic();
                topic.setId(rs.getInt("topic_id"));
                topic.setTitle(rs.getString("title"));
                topic.setDescribe(rs.getString("describe"));

                Category category = new Category();
                category.setName(rs.getString("category_name"));
                topic.setCategory(category);

                Photo photo = new Photo();
                photo.setImg(rs.getString("img"));
                topic.setPhoto(photo);

                topics.add(topic);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return topics;
    }

    @Override
    public Integer getCount(Integer tagId) {
        Integer p=0;
        String sql = "SELECT count(tag_id) from t_topic_tag WHERE tag_id=?";
        ResultSet rs = getObject(sql, tagId);
        try {
            while (rs.next()){
                p=rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return p;
    }

}
